﻿package  {
	
	import flash.net.*;
	import flash.utils.ByteArray;
	import com.serialization.json.*;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	
	public class Network {
		public var scriptUrl:String = "http://testhost.dev/swfgame/connector.php";
		public var Data:Object;
		
		public var onSuccess:Function;
		public var onError:Function;
		public var lastError:String;
		

		private var busy:Boolean = false;
		
		private var ldr:URLLoader;
		
		public function Network() {
			this.Data = new Object();
		}
		
		public function sendRequest(params:Object, _onSuccess:Function = null, _onError:Function = null):void
		{
			if(busy)
				return;
			this.ldr = new URLLoader();
			this.ldr.dataFormat = URLLoaderDataFormat.BINARY;
			this.onSuccess = function(e=null){};
			this.onError = function(e=null){};
			if(_onSuccess != null)
			{
				this.onSuccess = _onSuccess;
			}
			if(_onError != null)
			{
				this.onError = _onError;
			}
			
			var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
			var req:URLRequest = new URLRequest();
			req.requestHeaders.push(header);
			req.url = this.scriptUrl;
			req.method = URLRequestMethod.POST;
			
			this.ldr.removeEventListener(Event.COMPLETE, this.hSuccess);
			this.ldr.removeEventListener(IOErrorEvent.IO_ERROR, this.hError);
			this.ldr.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.hSecurity);
			
			this.ldr.addEventListener(Event.COMPLETE, this.hSuccess);
			this.ldr.addEventListener(IOErrorEvent.IO_ERROR, this.hError);
			this.ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.hSecurity);
			
			var dat:ByteArray = Helper.pack_data(params);
			req.data = dat;
			this.busy = true;
			this.ldr.load(req);
		}
		
		private function hSuccess(e:Event):void
		{
			this.busy = false;
			var dat:ByteArray = e.target.data;
			this.Data = Helper.unpack_data(dat);

			if(this.Data == null)
			{
				this.onError('WRONG_DATA');
				return;
			}
			this.onSuccess(this.Data);
			return;
		}
		
		private function hError(e:IOErrorEvent):void
		{
			this.busy = false;
			this.onError('IO_ERROR');
		}
		
		private function hSecurity(e:SecurityErrorEvent):void
		{
			this.busy = false;
			this.onError('SECURITY_ERROR');
		}
		
		
		
		
		

	}
	
}
